<?php
/**
 * Created by PhpStorm.
 * User: m3lony
 * Date: 2020/4/9 0009
 * Time: 下午 6:28
 */

namespace app\common\service;


use app\common\tools\Redis;
use library\tools\Http;
use WeChat\Contracts\BasicWeChat;

class Live
{
    /**
     * 获取直播间列表
     * @param string $start 起始拉取房间位置，start = 0 表示从第1个直播间开始拉取
     * @param string $limit 每次拉取的个数上限，不要设置过大，建议 100 以内
     * @return bool|array
     */
    public static function getLiveList($start,$limit){
        $redis = Redis::getRedis();
        $info = $redis->get('live');
        if ($info){
            return unserialize($info);
        } else {
            $accessToken = self::accessToken();
            $url = 'http://api.weixin.qq.com/wxa/business/getliveinfo?access_token=' . $accessToken;
            $data = ['start' => $start, 'limit' => $limit];
            $result = json_decode(Http::post($url, json_encode($data)), true)['room_info'];
            foreach ($result as $key => $value){
                $result[$key]['start_time'] = ['text' => date('m-d H:i',$value['start_time']), 'value' => $value['start_time']];
                $result[$key]['end_time'] = ['text' => date('m-d H:i',$value['end_time']), 'value' => $value['end_time']];
            }
            //  设置redis 5分钟更新一次数据
            $redis->setex('live', 300, serialize($result));
            return unserialize($redis->get('live'));
        }
    }

    /**
     * 获取回放列表
     * @param string $room_id 直播间ID
     * @param string $start 起始拉取视频，start = 0 表示从第1个视频片段开始拉取
     * @param string $limit 每次拉取的个数上限，不要设置过大，建议 100 以内
     * @return bool|array
     */
    public static function getReply($room_id,$start,$limit){
        $redis = Redis::getRedis();
        $info = $redis->get('reply');
        if ($info){
            return unserialize($info);
        } else {
            $accessToken = self::accessToken();
            $url = 'http://api.weixin.qq.com/wxa/business/getliveinfo?access_token=' . $accessToken;
            $data = [
                'action'  => 'get_replay',
                'room_id' => $room_id,
                'start'   => $start,
                'limit'   => $limit
            ];
            $result = json_decode(Http::post($url, json_encode($data)), true);
            //  设置redis 5分钟更新一次数据
            $redis->setex('reply', 300, serialize($result));
            return unserialize($redis->get('reply'));
        }
    }

    /**
     * 获取AccessToken
     */
    protected static function accessToken()
    {
        $config = ['appid' => sysconf('wechat_mini_appid'), 'appsecret' => sysconf('wechat_mini_appsecret')];
        $option = new BasicWeChat($config);
        return $option->getAccessToken();
    }
}